﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Net;
using System.Data.Linq;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Threading.Tasks;
using System.Threading;
using System.Web;
using HtmlAgilityPack;
using System.Linq.Expressions;
using CrawlerCore;

namespace WCrawlerLib
{
    partial class WapCrawler
    {
        LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public WapCrawler Get(int id)
        {
            return dc.WapCrawlers.Single(q => q.wapCrawlerId == id);
        }
    }

    partial class PostCrawler
    {
        LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public bool IsExist(string url)
        {
            bool result = false;
            var query = from p in dc.PostCrawlers
                        where p.postUrl == url
                        select p;
            if (query.Count() > 0)
                result = true;
            return result;
        }

        public PostCrawler Get(string url)
        {
            return dc.PostCrawlers.Single(q => q.postUrl == url);
        }

        public PostCrawler Insert(string title, string url, string head, string content, int pageId)
        {
            PostCrawler post = new PostCrawler();
            post.postTitle = title;
            post.postUrl = url;
            post.postHead = head;
            post.postContent = content;
            dc.PostCrawlers.InsertOnSubmit(post);
            dc.SubmitChanges();
            return post;
        }

        public PostCrawler Update()
        {
            dc.SubmitChanges();
            return this;
        }
    }

    partial class ForumGroup
    {
        LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public IQueryable<ForumGroup> GetAll()
        {
            var query = from p in dc.ForumGroups
                        select p;
            return query;
        }

    }

    partial class User
    {
        LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public bool CheckLogin(string username, string password)
        {
            int count = (from p in dc.Users
                           where p.UserName == username
                           && p.Password == password
                           select p).Count();
            return count == 1;
        }
    }

    partial class ImagePost
    {
        LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public void AddOriginalUrl(int postId, Dictionary<string, string> imageDict, bool isPoster)
        {
            foreach (KeyValuePair<string, string> image in imageDict)
            {
                ImagePost imgPost = new ImagePost();
                imgPost.ImageTitle = image.Key;
                imgPost.IsPoster = isPoster;
                imgPost.OriginalUrl = image.Value;
                imgPost.PostId = postId;
                dc.ImagePosts.InsertOnSubmit(imgPost);
            }
            dc.SubmitChanges();
        }

        public void AddImageUrl(int postId, Dictionary<string, string> imageDict, bool isPoster)
        {
            foreach (KeyValuePair<string, string> image in imageDict)
            {
                ImagePost imgPost = new ImagePost();
                imgPost.ImageTitle = image.Key;
                imgPost.IsPoster = isPoster;
                imgPost.ImageUrl = image.Value;
                imgPost.PostId = postId;
                dc.ImagePosts.InsertOnSubmit(imgPost);
            }
            dc.SubmitChanges();
        }

        public ImagePost GetImagePost(int imgPostId)
        {
            ImagePost imgPost = dc.ImagePosts.Single(q => q.ImagePostId == imgPostId);
            return imgPost;
        }

        public void UpdateImageUrl(string imgUrl)
        {
            ImagePost imgPost = GetImagePost(ImagePostId);
            imgPost.ImageUrl = imgUrl;
            dc.SubmitChanges();
        }

        public IQueryable<ImagePost> GetImagesByPost(int postId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.ImagePosts
                        where p.PostId == postId
                        select p;
            return query;
        }

        /// <summary>
        /// Get images with tag [IMG]
        /// </summary>
        /// <param name="postId"></param>
        /// <returns>return 2 type image are POSTER and SCREENSHOTS</returns>
        public Dictionary<int, string> GetImagesByPostWithTag(int postId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.ImagePosts
                        where p.PostId == postId
                        select p;
            Dictionary<int, string> imgDict = new Dictionary<int, string>();
            imgDict.Add(0, "");
            imgDict.Add(1, "");
            string screenShots = "";
            foreach (ImagePost imgPost in query)
            {
                if (imgPost.IsPoster)
                    imgDict[0] = string.Format("[IMG]{0}[/IMG]\n", imgPost.ImageUrl);
                else{
                    screenShots += string.Format("[IMG]{0}[/IMG]\n", imgPost.ImageUrl);
                }
            }
            imgDict[1] = screenShots;
            return imgDict;
        }
    }

    partial class ForumHost
    {
        public IQueryable<ForumHost> GetForumHostIconByForum(int forumId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.ForumHosts
                        where p.ForumId == forumId
                        select p;
            return query;
        }

        public ForumHost AddForumHostIcon(int forumId, int hostId, int iconNumber)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumHost objForumHost = new ForumHost
            {
                ForumId = forumId,
                HostId = hostId,
                IconNumber = iconNumber
            };
            dc.ForumHosts.InsertOnSubmit(objForumHost);
            dc.SubmitChanges();
            return objForumHost;
        }
    }

    partial class FilePost
    {
        public IQueryable<FilePost> GetFilePostsByPost(int postId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<FilePost> query = from p in dc.FilePosts
                                             where p.PostId == postId
                                             select p;
            return query;
        }

        /// <summary>
        /// Check files of postId are still alive or dead
        /// </summary>
        /// <param name="postId"></param>
        /// <returns></returns>
        public bool CheckFilesAlive(int postId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<FilePost> query = from p in dc.FilePosts
                                         where p.PostId == postId && p.IsAlive == true
                                         select p;
            bool result = false;
            if (query.Count() > 0)
                result = true;
            return result;
        }

        /// <summary>
        /// Check exactly every file of postId is still alive or dead
        /// </summary>
        /// <param name="postId"></param>
        /// <returns></returns>
        public Dictionary<string, string> CheckFilePostsByPost(int postId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<FilePost> query = from p in dc.FilePosts
                                         where p.PostId == postId
                                         select p;
            //Get exactly files is alive or dead
            Dictionary<string, string> finalChecklinks = new Dictionary<string, string>();
            object objLock = new object();
            //Every hostId check files is alive or dead
            Parallel.ForEach(query, p =>
            {
                BrowserSession_FileHost br = new BrowserSession_FileHost();
                Dictionary<string, string> checklinks = br.CheckLinks(p.HostId.Value, p.FilesUrl.Trim());
                bool result = true;
                
                lock (objLock)
                {
                    foreach (KeyValuePair<string, string> file in checklinks)
                    {
                        //if exist any file is dead then set result is false
                        if (file.Value == "Dead")
                            result = false;
                        finalChecklinks.Add(file.Key, file.Value);
                    }

                    //Save status into database
                    FilePost objFilePost = dc.FilePosts.Single(q => q.FilePostId == p.FilePostId);
                    objFilePost.IsAlive = result;
                    dc.SubmitChanges();
                }
            });
            return finalChecklinks;
        }

        public string GetHtmlCode(int postId, bool useHideTag, bool isHostContraint)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            //Get files is alive
            IQueryable<FilePost> query = from p in dc.FilePosts
                                             where p.PostId == postId && p.IsAlive == true
                                             select p;

            string htmlCode = "";
            foreach (FilePost files in query)
            {
                string fileUrls = files.FilesUrl;
                //if the forum contraint host file then add white space in hostname. 
                //For example, "filesonic" after add white space "f ilesonic"
                if (isHostContraint)
                {
                    string hostName = GeneralClass.GetName(files.FilesUrl);
                    //add white space in hostName
                    string replaceHostName = hostName.Substring(0, 1) + " " + hostName.Substring(1, hostName.Length - 1);
                    fileUrls = files.FilesUrl.Replace(hostName, replaceHostName);
                }
                htmlCode += "[CODE]" + fileUrls + "[/CODE]\n";
            }

            //Use hide tag
            if (useHideTag)
                htmlCode = "[HIDE]" + htmlCode + "[/HIDE]";

            //htmlCode = "[B][U]Download links:[/U][/B]\n" + htmlCode;
            return htmlCode;
        }

        public FilePost AddFilePosts(int postId, int hostId, string files)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            FilePost objFilePost = new FilePost
            {
                PostId = postId,
                HostId = hostId,
                FilesUrl = files
            };
            dc.FilePosts.InsertOnSubmit(objFilePost);
            dc.SubmitChanges();
            return objFilePost;
        }

        public List<string> RowDataBoundCheckLinks(string downloadFiles, Dictionary<string, string> checklinks)
        {
            List<string> fileList = new List<string>();
            string[] fileArray = downloadFiles.Trim().Split(new char[] { '\n' });
            
            if (checklinks != null)
            {
                foreach (string f in fileArray)
                {
                    string file = HttpUtility.UrlPathEncode(HttpUtility.HtmlDecode(f).Trim());
                    //if (file.Contains("http://depositfiles.com"))
                    //    file = file.Replace("http://depositfiles.com", "http://depositfiles.com/en");
                    
                    string url = "<a href=\"" + file + "\">" + file + "</a>";
                    var query = from p in checklinks.Keys.AsQueryable<string>()
                                where file.Contains(p)
                                select p;
                    if (query.Count() > 0)
                    {
                        foreach (string value in query)
                        {
                            if (checklinks[value] == "Working") 
                                url = "<a style=\"color:#368a30; text-decoration: none;\" href=\"" + file + "\">" + file + "</a>" + "&nbsp<font size=\"3\" face=\"times\" color=\"gray\">" + checklinks[value] + "</font>";
                            else //dead
                                url = "<a style=\"color:#FF0000; text-decoration: none;\" href=\"" + file + "\">" + file + "</a>" + "&nbsp<font size=\"3\" face=\"times\" color=\"red\">" + checklinks[value] + "</font>";
                        }
                    }
                    fileList.Add(url);
                }
            }
            else
            {
                foreach (string file in fileArray)
                {
                    string url;
                    url = "<a href=\"" + file + "\">" + file + "</a>";
                    fileList.Add(url);
                }
            }
            return fileList;
        }
    }

    /// <summary>
    /// Test repository
    /// </summary>
    partial class Host
    {
        private BrowserSession_General _browser;
        public BrowserSession_General Browser
        {
            get
            {
                if (_browser == null)
                    _browser = new BrowserSession_General();
                return _browser;
            }
            set
            {
                _browser = value;
            }
        }

        /// <summary>
        /// Get alexa rank and location of a host
        /// </summary>
        public void UpdateAlexaRankAndLocation()
        {
            //*********************************************************************************
            //GET ALEXA RANK & LOCATION
            //*********************************************************************************
            Dictionary<string, string> alexa = Browser.GetAlexaRank(HostUrl);
            if (alexa["rank"] != "")
                AlexaRank = int.Parse(alexa["rank"]);
            if (alexa["location"] != "")
            {
                Location loc = new Location();
                LocationId = loc.GetLocationId(alexa["location"]);
            }
        }

        public void UpdateInformation(int hostId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Host objHost = dc.Hosts.Single(p => p.HostId == hostId);
            objHost.UpdateAlexaRankAndLocation();
            dc.SubmitChanges();
        }

        public void Update(int hostId, string hostName, string hostUrl)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Host objHost = dc.Hosts.Single(p => p.HostId == hostId);
            objHost.HostUrl = hostUrl;
            objHost.HostName = hostName;
            dc.SubmitChanges();
        }

        public void AddHost(string hostName, string hostUrl)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Host objHost = new Host
            {
                HostName = hostName,
                HostUrl = hostUrl
            };
            dc.Hosts.InsertOnSubmit(objHost);
            dc.SubmitChanges();
        }

        public bool IsExist(string hostName)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            bool result = false;
            var query = from p in dc.Hosts
                        where p.HostName.ToLower() == hostName.ToLower()
                        select p;
            if (query.Count() > 0)
                result = true;
            return result;
        }

        public Host GetHost(int hostId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Host objHost = dc.Hosts.Single(p => p.HostId == hostId);
            return objHost;
        }

        
        public Host GetHost(string hostName)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Host objHost = null;
            try
            {
                objHost = dc.Hosts.Single(p => p.HostName.ToLower() == hostName.ToLower());
            }
            catch
            {

            }
            return objHost;
        }
    }

    partial class Template
    {
        LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public bool IsExist(int templateId)
        {
            bool result = false;
            IQueryable<Template> query = from q in dc.Templates
                                         where q.TemplateId == templateId
                                         select q;
            if (query.Count() > 0)
                result = true;
            return result;
        }

        public bool AddTemplate(string templateName)
        {
            bool result = false;
            var query = from p in dc.Templates
                        where p.TemplateName == templateName
                        select p;
            if (query.Count() == 0)
            {
                Template objTemplate = new Template
                {
                    TemplateName = templateName
                };
                dc.Templates.InsertOnSubmit(objTemplate);
                dc.SubmitChanges();
                result = true;
            }
            return result;
        }

        public IQueryable<Template> GetAllTemplates()
        {
            var query = from p in dc.Templates
                        select p;
            return query;
        }
    }

    partial class TemplateDetail
    {
        

        public TemplateDetail AddTemplateDetails(int forumTypeId, int templateId, string templatePattern, bool isDefault)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            TemplateDetail objTemplateDetail = new TemplateDetail
            {
                ForumTypeId = forumTypeId,
                TemplateId = templateId,
                TemplatePattern = templatePattern,
                IsDefault = isDefault
            };

            dc.TemplateDetails.InsertOnSubmit(objTemplateDetail);
            dc.SubmitChanges();
            return objTemplateDetail;
        }

        /// <summary>
        /// Update black list title for all forumtypes
        /// </summary>
        /// <param name="title"></param>
        public void UpdateBlackListTitle(string blacklistTitle)
        {
            int templateId = 7;
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            //Get default value
            IQueryable<TemplateDetail> query = from q in dc.TemplateDetails
                                               where (q.ForumTypeId == (int)enumForumType.vBulletin3x
                                                       || q.ForumTypeId == (int)enumForumType.vBulletin4x
                                                       || q.ForumTypeId == (int)enumForumType.phpBB2
                                                       || q.ForumTypeId == (int)enumForumType.phpBB3
                                                       || q.ForumTypeId == (int)enumForumType.IPB
                                                       || q.ForumTypeId == (int)enumForumType.myBB)
                                                   && q.TemplateId == templateId
                                               select q;
            blacklistTitle = blacklistTitle.ToLower().Trim();
            foreach (TemplateDetail obj in query)
            {
                if (!string.IsNullOrEmpty(obj.TemplatePattern))
                {
                    if (!obj.TemplatePattern.Contains(blacklistTitle))
                        obj.TemplatePattern += "|" + blacklistTitle;
                }
                else
                    obj.TemplatePattern = blacklistTitle;
            }
            dc.SubmitChanges();
        }

        public IQueryable<TemplateDetail> GetTemplateDetailsByForumType(int? forumTypeId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            //Get default value
            IQueryable<TemplateDetail> query = from q in dc.TemplateDetails
                                               where q.ForumTypeId == forumTypeId
                                                  //&& q.IsDefault.Value
                                               select q;
            return query;
        }

        public IQueryable<TemplateDetail> GetTemplateDetails(int? forumTypeId, int templateId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<TemplateDetail> query = from q in dc.TemplateDetails
                                               where q.ForumTypeId == forumTypeId
                                               && q.TemplateId == templateId
                                               select q;
            return query;
        }

        public TemplateDetail GetTemplateDetails(int templateDetailsId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            //Get default value
            TemplateDetail objDefault = dc.TemplateDetails.Single(q => q.TemplateDetailsId == templateDetailsId);
            return objDefault;
        }

        /// <summary>
        /// Get remaining templates detail which the forum hasn't had yet
        /// </summary>
        /// <param name="forumId"></param>
        /// <param name="forumTypeId"></param>
        /// <returns></returns>
        public IQueryable<TemplateDetail> GetRemainingTemplateDetailsOfForum(int forumId, int forumTypeId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            //Get default value
            //TemplateDetail objTempDetail = new WCrawlerLib.TemplateDetail();
            //Get default template doensn't have yet
            var queryTemplateId = from p in dc.ForumTemplateDetails
                                  where p.ForumId == forumId
                                  select p.TemplateDetail.TemplateId;

            IQueryable<TemplateDetail> query = from q in dc.TemplateDetails
                                               where q.ForumTypeId == forumTypeId
                                                 && !queryTemplateId.Contains(q.TemplateId)
                                               select q;
            return query;
        }

        /// <summary>
        /// Get remaining templates detail which the forum hasn't had yet
        /// 
        /// </summary>
        /// <param name="forumId"></param>
        /// <param name="forumTypeId"></param>
        /// <returns></returns>
        public IQueryable<TemplateDetail> GetTemplateDetailsByTemplateId(int forumTypeId, int templateDetailsId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            TemplateDetail objTemplateDetails = dc.TemplateDetails.Single(p => p.TemplateDetailsId == templateDetailsId);
            IQueryable<TemplateDetail> query = from q in dc.TemplateDetails
                                               where q.ForumTypeId == forumTypeId
                                               && q.TemplateId == objTemplateDetails.TemplateId
                                               && q.TemplateDetailsId != templateDetailsId
                                               select q;
            return query;
        }
    }

    partial class ForumTemplateDetail
    {
        public bool IsExist(int templateDetailsId, int forumId)
        {
            bool result = false;
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<ForumTemplateDetail> query = from q in dc.ForumTemplateDetails
                                                    where q.ForumId == forumId 
                                                    && q.TemplateDetailsId == templateDetailsId
                                                    select q;
            if (query.Count() > 0)
                result = true;
            return result;
        }

        public IQueryable<ForumTemplateDetail> GetForumTemplateDetailsByForum(int forumId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<ForumTemplateDetail> query = from q in dc.ForumTemplateDetails
                                               where q.ForumId == forumId
                                               select q;
            return query;
        }

        public ForumTemplateDetail Add(int templateDetailsId, int forumId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumTemplateDetail objForumTemplate = new ForumTemplateDetail
            {
                TemplateDetailsId = templateDetailsId,
                ForumId = forumId
            };
            dc.ForumTemplateDetails.InsertOnSubmit(objForumTemplate);
            dc.SubmitChanges();
            return objForumTemplate;
        }

        public void Delete(int templateDetailsId, int forumId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumTemplateDetail objForumTemplate = dc.ForumTemplateDetails.Single(p => p.TemplateDetailsId == templateDetailsId && p.ForumId == forumId);
            dc.ForumTemplateDetails.DeleteOnSubmit(objForumTemplate);
            dc.SubmitChanges();
        }

        

        /// <summary>
        /// Add default template for a forum if doesn't have yet
        /// </summary>
        /// <param name="forumId"></param>
        /// <param name="forumTypeId"></param>
        public void UpdateDefaultForumTemplate(int forumId, int forumTypeId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            TemplateDetail objTemplateDetails = new WCrawlerLib.TemplateDetail();
            var query = from p in objTemplateDetails.GetRemainingTemplateDetailsOfForum(forumId, forumTypeId)
                        where p.IsDefault.Value
                        select p.TemplateDetailsId;
            //Insert
            foreach (int templateDetailsId in query)
            {
                ForumTemplateDetail objForumTempDetail = new ForumTemplateDetail
                {
                    ForumId = forumId,
                    TemplateDetailsId = templateDetailsId
                };
                dc.ForumTemplateDetails.InsertOnSubmit(objForumTempDetail);
            }
            dc.SubmitChanges();
        }

        private string GetTemplate(int forumId, int? forumTypeId, int templateId)
        {
            string value = "";
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumTemplateDetail obj = new ForumTemplateDetail();
            try
            {
                obj = dc.ForumTemplateDetails.Single(p => p.ForumId == forumId && p.TemplateDetail.TemplateId == templateId);
                value = obj.TemplateDetail.TemplatePattern;
            }
            catch
            {
                //if forumId don't have templateId then add default templates again
                UpdateDefaultForumTemplate(forumId, forumTypeId.Value);
                try
                {
                    obj = dc.ForumTemplateDetails.Single(p => p.ForumId == forumId && p.TemplateDetail.TemplateId == templateId);
                    value = obj.TemplateDetail.TemplatePattern;
                }
                catch
                {

                }
            }
            return value;
        }

        public string GetLoginUrl(int forumId, int? forumTypeId)
        {
            string loginUrl = GetTemplate(forumId, forumTypeId, 1);
            return loginUrl;
        }

        public string GetRegisterUrl(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 2);
            return template;
        }

        public string GetStatisticUrl(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 3);
            return template;
        }

        public string GetNewThreadUrl(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 4);
            return template;
        }

        public string GetNewReplyUrl(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 5);
            return template;
        }

        public string GetBlackList_Pattern(int forumId, int? forumTypeId)
        {
            string value = GetTemplate(forumId, forumTypeId, 6);
            //if (!string.IsNullOrEmpty(value))
            //    value = "(" + value.Replace(@".", @"\.").Replace(@"/",@"\/") + ")";
            return value;
        }

        public string GetBlackListTopic(int forumId, int? forumTypeId)
        {
            string value = GetTemplate(forumId, forumTypeId, 7);
            return value;
        }

        public string GetUserCPUrl_Get(int forumId, int? forumTypeId)
        {
            string value = GetTemplate(forumId, forumTypeId, 10);
            return value;
        }

        public string GetLogin_Params(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 18);
            return template;
        }

        public string GetPostNewThread_Params(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 11);
            return template;
        }

        public string GetPostReply_Params(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 12);
            return template;
        }

        public string GetPostEdit_Params(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 13);
            return template;
        }

        public string GetSearchThreadsPattern_Params(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 14);
            return template;
        }

        public string GetSearchTopicUrl_XPath(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 22);
            return template;
        }

        public string GetSearchThreadUrl_XPath(int forumId, int? forumTypeId)
        {
            string template = GetTemplate(forumId, forumTypeId, 23);
            return template;
        }

        //public string GetPostIdPatternParams(int forumId, int? forumTypeId)
        //{
        //    string template = GetTemplate(forumId, forumTypeId, 17);
        //    return template;
        //}
    }

    partial class Topic
    {
        public LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public Topic GetTopic(string topicName)
        {
            Topic obj = dc.Topics.Single(p => p.TopicName == topicName);
            return obj;
        }

        public Topic GetTopic(int topicId)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Topic obj = dc.Topics.Single(p => p.TopicId == topicId);
            return obj;
        }

        public IQueryable<Topic> GetRootTopics()
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.Topics
                        where p.ParentTopicId == null
                        select p;
            return query;
        }

        /// <summary>
        /// Get root topic with topicId
        /// </summary>
        /// <param name="topicId"></param>
        /// <returns></returns>
        public Topic GetRootTopic(int? topicId)
        {
            Topic obj = dc.Topics.Single(p => p.TopicId == topicId);
            if (obj.ParentTopicId != null)
                obj = GetRootTopic(obj.ParentTopicId);
            return obj;
        }

        public IQueryable<Topic> GetChildTopics(int parentTopicId)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.Topics
                        where p.ParentTopicId == parentTopicId
                        select p;
            return query;
        }

        public void GetAllChildTopics(int parentTopicId, ref List<Topic> topicList)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<Topic> query =   from p in dc.Topics
                                        where p.ParentTopicId == parentTopicId
                                        select p;

            foreach (Topic objTopic in query)
            {
                topicList.Add(objTopic);
                GetAllChildTopics(objTopic.TopicId, ref topicList);
            }
        }

        public void UpdateTopic(Topic objTopic)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Topic q = dc.Topics.Single(p => p.TopicId == objTopic.TopicId);
            q.TopicName = objTopic.TopicName;
            q.ParentTopicId = objTopic.ParentTopicId;
            q.TopicOrder = objTopic.TopicOrder;
            q.Keywords = objTopic.Keywords;
            dc.SubmitChanges();
        }

        /// <summary>
        /// Add new thread. 
        /// If add successful return id else return -1
        /// </summary>
        /// <param name="objTopic"></param>
        /// <returns></returns>
        public int AddTopic(Topic objTopic)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.Topics
                        where p.TopicName.Contains(objTopic.TopicName)
                        select p;
            if (query.Count() == 0) //If not found then insert
            {
                dc.Topics.InsertOnSubmit(objTopic);
                dc.SubmitChanges();
                return objTopic.TopicId;
            }
            return -1;
        }

        public IQueryable<Topic> GetTopicsByQuery(string topicIds)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            List<string> topicIdList = topicIds.Split(new char[] { '|' }).ToList();
            IQueryable<Topic> query = (from p in dc.Topics
                                            where topicIdList.Contains(p.TopicId.ToString())
                                            select p).OrderBy(t => t.TopicOrder);

            return query;
        }

        public IQueryable<Topic> GetAllTopics()
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<Topic> query = (from p in dc.Topics
                                       select p).OrderBy(t => t.TopicOrder);

            return query;
        }
    }

    partial class ForumTopic
    {
        public ForumTopic GetForumTopic(int forumId, int topicId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumTopic obj = dc.ForumTopics.Single(p=>p.TopicId == topicId && p.ForumId == forumId);
            return obj;
        }

        //public IQueryable<ForumTopic> GetRootTopics(int forumId)
        //{
        //    LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        //    var query = from p in dc.ForumTopics
        //                where p.Topic.ParentTopicId == null && p.ForumId == forumId
        //                select p;
        //    return query;
        //}

        //public IQueryable<ForumTopic> GetChildTopics(int forumId, int parentTopicId)
        //{
        //    LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        //    var query = from p in dc.ForumTopics
        //                where p.Topic.ParentTopicId == parentTopicId && p.ForumId == forumId
        //                select p;
        //    return query;
        //}

        public IQueryable<ForumTopic> GetTopicsByForum(int forumId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<ForumTopic> query = dc.ForumTopics.Where(p => p.ForumId == forumId);
            return query;
        }

        //public IQueryable<ForumTopic> GetTopicsByQuery(int forumId, string threadIds)
        //{
        //    LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        //    IQueryable<ForumTopic> query = dc.ForumTopics.Where(p => p.ForumId == forumId);
        //    List<string> threadList = threadIds.Split(new char[] { '|' }).ToList();
        //    var predicate = PredicateBuilder.True<ForumTopic>();
        //    foreach (string topicId in threadList)
        //    {
        //        int id = int.Parse(topicId);
        //        predicate = predicate.Or(p => p.TopicId == id);
        //    }
        //    query = query.Where(predicate);//.OrderBy(t => t.Topic.ParentTopicId);

        //    return query;
        //}

        
        public IQueryable<ForumTopic> GetTopicsByQuery(int forumId, string topicIds)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            List<string> topicIdList = topicIds.Split(new char[] { '|' }).ToList();
            IQueryable<ForumTopic> query = (from p in dc.ForumTopics
                                            where p.ForumId == forumId
                                            && topicIdList.Contains(p.TopicId.ToString())
                                            select p).OrderBy(t => t.Topic.TopicOrder);
            
            return query;
        }

        public void UpdateTopics(int forumId, int topicId, string topicUrl, string topicName, int? fvalue)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumTopic q = dc.ForumTopics.Single(p => p.ForumId == forumId
                                                     && p.TopicId == topicId);
            if (q != null) //If found then update
            {
                q.ForumTopicUrl = topicUrl;
                q.ForumTopicName = topicName;
                q.fValue = fvalue;
            }
            else //If not found then insert
            {
                q = new ForumTopic
                {
                    _ForumId = forumId,
                    _TopicId = topicId,
                    _ForumTopicName = topicName,
                    _ForumTopicUrl = topicUrl,
                    _fValue = fvalue
                };
                dc.ForumTopics.InsertOnSubmit(q);
            }
            dc.SubmitChanges();
        }

        public void UpdateTopics(ForumTopic objForumTopic)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumTopic q = dc.ForumTopics.Single(p => p.ForumId == objForumTopic.ForumId
                                                                && p.TopicId == objForumTopic.TopicId);
            if (q != null) //If found then update
            {
                q.ForumTopicUrl = objForumTopic.ForumTopicUrl;
                q.ForumTopicName = objForumTopic.ForumTopicName;
                q.fValue = objForumTopic.fValue;
                q.Prefix = objForumTopic.Prefix;
            }
            else //If not found then insert
            {
                q = new ForumTopic
                {
                    _ForumId = objForumTopic.ForumId,
                    _TopicId = objForumTopic.TopicId,
                    _ForumTopicName = objForumTopic.ForumTopicName,
                    _ForumTopicUrl = objForumTopic.ForumTopicUrl,
                    _fValue = objForumTopic.fValue,
                    _Prefix = objForumTopic.Prefix
                };
                dc.ForumTopics.InsertOnSubmit(q);
            }
            dc.SubmitChanges();
        }

        public void SychronizeTopics(int forumId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            //select topics of forum
            var queryForumTopics =  from p in dc.ForumTopics
                                where p.ForumId == forumId
                                select p.TopicId;

            //select all topics
            var queryTopics = from p in dc.Topics
                               where !queryForumTopics.Contains(p.TopicId)
                               select p;

            foreach (Topic obj in queryTopics)
            {
                ForumTopic objForumTopic = new ForumTopic();
                objForumTopic.TopicId = obj.TopicId;
                objForumTopic.ForumId = forumId;
                dc.ForumTopics.InsertOnSubmit(objForumTopic);
            }
            dc.SubmitChanges();
        }

        /// <summary>
        /// Xử lý phân cấp lấy fId để post new thread
        /// Ví dụ: Game là mức cha của PcGame, XBoxGame, PsxGame
        /// Post new thread về PcGame,
        /// nếu PcGame Topic mà không có thì sẽ post cho Game Topic ở mức cha.
        /// </summary>
        /// <param name="topicId"></param>
        public ForumTopic GetExactlyPostTopicValue(int forumId, int? topicId)
        {
            ForumTopic objForumTopic = null;
            if (topicId.HasValue)
            {
                LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
                //Synchornize threads of a forum
                SychronizeTopics(forumId);
                objForumTopic = dc.ForumTopics.Single(p => p.TopicId == topicId.Value
                                                            && p.ForumId == forumId);
                //If fvalue hasn't value then continue found at parent thread
                if (!objForumTopic.fValue.HasValue)
                {
                    //if (objForumTopic.Topic != null)
                    objForumTopic = GetExactlyPostTopicValue(forumId, objForumTopic.Topic.ParentTopicId);
                }
            }
            return objForumTopic;
            
        }
    }

    partial class ForumThread
    {
        private LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public IQueryable<ForumThread> GetAll()
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.ForumThreads
                        select p;
            return query;
        }

        public IQueryable<ForumThread> GetForumThreadByForum(int forumId)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.ForumThreads
                        where p.ForumId == forumId
                        select p;
            return query;
        }

        public ForumThread UpdateForumThread(int postId, int forumId, ForumThread obj)
        {
            //Check ThreadPost is exist in primary post of a thread?
            //var query = from p in dc.ForumThreads
            //            where p.ForumId == obj.ForumId 
            //            && p.ThreadTitle.Trim().ToLower() == obj.ThreadTitle.Trim().ToLower()
            //            select p;

            ForumThread objForumThread = GetForumThread(postId, forumId);
            if (objForumThread == null)
                dc.ForumThreads.InsertOnSubmit(obj);
            else
            {
                objForumThread.ForumId = obj.ForumId;
                objForumThread.ThreadNum = obj.ThreadNum;
                objForumThread.ThreadTitle = obj.ThreadTitle;
                objForumThread.ThreadUrl = obj.ThreadUrl;
                objForumThread.Replies = obj.Replies;
                objForumThread.Views = obj.Views;
            }
            dc.SubmitChanges();
            return obj;
        }

        /// <summary>
        /// just update threadurl, views, replies
        /// </summary>
        /// <returns></returns>
        public void UpdateForumThread(int forumId, int threadNum, string threadTitle, string threadUrl, int replies, int views)
        {
            ForumId = forumId;
            ThreadNum = threadNum;
            ThreadTitle = threadTitle;
            ThreadUrl = threadUrl;
            Replies = replies;
            Views = views;

            dc.SubmitChanges();
        }

        /// <summary>
        /// Delete ForumThread
        /// </summary>
        /// <returns></returns>
        public void DeleteForumThread(int forumThreadId)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumThread objForumThread = dc.ForumThreads.Single(p => p.ForumThreadId == forumThreadId);
            dc.ForumThreads.DeleteOnSubmit(objForumThread);
            dc.SubmitChanges();
        }

        /// <summary>
        /// just update threadurl, views, replies
        /// </summary>
        /// <returns></returns>
        public void UpdateThreadNum(int forumThreadId, int threadNum)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumThread objForumThread = dc.ForumThreads.Single(p => p.ForumThreadId == forumThreadId);
            objForumThread.ThreadNum = threadNum;
            dc.SubmitChanges();
        }

        /// <summary>
        /// Get ForumThreads with postId is primary post
        /// </summary>
        /// <param name="postId"></param>
        /// <param name="forumId"></param>
        /// <returns></returns>
        public ForumThread GetForumThread(int postId, int forumId)
        {
            ForumThread objForumThread = null;
            var query = from q in dc.ThreadPosts
                        where q.PostDetail.PostId == postId
                            && q.IsFirstPost.Value == true
                            && q.ForumThread.ForumId == forumId
                        select q.ForumThread;
            foreach (ForumThread obj in query)
                objForumThread = obj;

            return objForumThread;
        }

        /// <summary>
        /// Get ForumThreads with postId is primary post
        /// </summary>
        /// <param name="postId"></param>
        /// <param name="forumId"></param>
        /// <returns></returns>
        public ForumThread GetForumThread(int forumThreadId)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumThread objForumThread = dc.ForumThreads.Single(p=>p.ForumThreadId == forumThreadId);
            return objForumThread;
        }

        /// <summary>
        /// Get ForumThreads with postId is primary post
        /// </summary>
        /// <param name="postId"></param>
        /// <param name="forumId"></param>
        /// <returns></returns>
        public IQueryable<ForumThread> GetForumThreadsByPost(int postId, string groupId, int status)
        {
            Forum obj = new Forum();
            IQueryable<Forum> forumsQuery = obj.GetPostedForums(postId, status)
                                 .WhereGroup(groupId)
                                 .IsApproved(true);

            List<int> queryForumIds = (from p in forumsQuery
                                   select p.ForumId).ToList();

            IQueryable<ForumThread> queryThreadPost = from q in dc.ThreadPosts
                                                      where q.PostDetail.PostId == postId
                                                         && q.IsFirstPost.Value == true
                                                         && queryForumIds.Contains(q.ForumThread.ForumId)
                                                      select q.ForumThread;
            return queryThreadPost;
        }

        public bool IsThreadNumExists(int forumId, int threadNum)
        {
            bool result = false;
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.ForumThreads
                        where p.ForumId == forumId && p.ThreadNum == threadNum
                        select p;
            if (query.Count() > 0)
                result = true;
            return result;
        }
    }

    partial class ThreadPost
    {
        private LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public IQueryable<ThreadPost> GetAll()
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.ThreadPosts
                        select p;
            return query;
        }

        public ThreadPost GetThreadPost(int forumThreadId, int postDetailsId)
        {
            //LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ThreadPost objThreadPost;
            try
            {
                objThreadPost = dc.ThreadPosts.Single(p => p.ForumThreadId == forumThreadId && p.PostDetailsId == postDetailsId);
            }
            catch
            {
                objThreadPost = null;
            }
            return objThreadPost;
        }

        public void UpdatePostNum(int forumThreadId, int postDetailsId, int postNum)
        {
            ThreadPost objThreadPost = GetThreadPost(forumThreadId, postDetailsId);
            objThreadPost.PostNum = postNum;
            dc.SubmitChanges();
        }

        public void UpdateThreadPost(int postDetailsId, int postNum)
        {
            PostDetailsId = postDetailsId;
            PostNum = postNum;
            dc.SubmitChanges();
        }
    }

    partial class PostDetail
    {
        public IQueryable<PostDetail> GetAll()
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.PostDetails
                        select p;
            return query;
        }

        public PostDetail GetPostDetail(int postDetailId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            PostDetail obj = dc.PostDetails.Single(p => p.PostDetailsId == postDetailId);
            return obj;
        }

        /// <summary>
        /// Get PostDetail by the language of the forum and thread title
        /// </summary>
        /// <param name="languageId"></param>
        /// <param name="postTitle"></param>
        /// <returns></returns>
        public PostDetail GetPostDetailByTitle(int languageId, string postTitle)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            PostDetail objPostDetail = null;
            //Find PostDetail with exactly language and PostTitle
            var query = from p in dc.PostDetails
                        where p.LanguageId == languageId
                            && p.PostTitle == postTitle
                        select p;

            if (query.Count() == 0 && languageId != (int)enumLanguage.English) //If not found then find with language != English
            {
                objPostDetail = GetPostDetailByTitle((int)enumLanguage.English, postTitle);
            }
            else //if found
            {
                foreach (PostDetail obj in query)
                    objPostDetail = obj;
            }
            return objPostDetail;
        }

        /// <summary>
        /// Xử lý phân cấp lấy fId để post new thread
        /// Ví dụ: Game là mức cha của PcGame, XBoxGame, PsxGame
        /// Post new thread về PcGame,
        /// nếu PcGame Topic mà không có thì sẽ post cho Game Topic ở mức cha.
        /// </summary>
        /// <param name="topicId"></param>
        public PostDetail GetExactlyPostDetail(int postId, int? languageId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            PostDetail objPostDetail = null;
            //Get exactly PostDetail with forumtype and language of the forum
            var query = from p in dc.PostDetails
                        where p.PostId == postId
                        && p.LanguageId == languageId
                        select p;
            //If not found then get language = english
            if (query.Count() == 0 && languageId != (int)enumLanguage.English)
            {
                objPostDetail = GetExactlyPostDetail(postId, (int)enumLanguage.English);
            }
            else
            {
                foreach (PostDetail obj in query)
                    objPostDetail = obj;
            }
            return objPostDetail;
        }

        /// <summary>
        /// Get html content with download files
        /// </summary>
        /// <returns></returns>
        public string GetFullHtmlContent(enumForumType forumTypeId, bool useHideTag, bool isHostContraint)
        {
            string fullHtmlContent = PostContent;
            //==================================================================================================================
            ImagePost objImgPost = new ImagePost();
            Dictionary<int, string> imgDict = objImgPost.GetImagesByPostWithTag(PostId.Value);
            //Get Poster Image
            fullHtmlContent = fullHtmlContent.Replace("[POSTER]", imgDict[0]);

            if (forumTypeId == enumForumType.phpBB3)
            {
                Regex r = new Regex("\\[SIZE\\=(\"|)(?<size>[0-9]+)(\"|)\\]");
                Match m = r.Match(fullHtmlContent);
                while (m.Success)
                {
                    int size = int.Parse(m.Result("${size}"));
                    switch (size)
                    {
                        case 1:
                            fullHtmlContent = fullHtmlContent.Replace(m.Value, "[SIZE=50]");
                            break;
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                            fullHtmlContent = fullHtmlContent.Replace(m.Value, "[SIZE=150]");
                            break;
                        case 6:
                        case 7:
                            fullHtmlContent = fullHtmlContent.Replace(m.Value, "[SIZE=200]");
                            break;
                        default:
                            break;
                    }
                    m = m.NextMatch();
                }
            }
            else if (forumTypeId == enumForumType.phpBB2)
            {
                Regex r = new Regex("\\[SIZE\\=(\"|)(?<size>[0-9]+)(\"|)\\]");
                Match m = r.Match(fullHtmlContent);
                while (m.Success)
                {
                    int size = int.Parse(m.Result("${size}"));
                    switch (size)
                    {
                        case 1:
                            fullHtmlContent = fullHtmlContent.Replace(m.Value, "[SIZE=7]");
                            break;
                        case 2:
                        case 3:
                        case 4:
                        case 5:
                            fullHtmlContent = fullHtmlContent.Replace(m.Value, "[SIZE=18]");
                            break;
                        case 6:
                        case 7:
                            fullHtmlContent = fullHtmlContent.Replace(m.Value, "[SIZE=24]");
                            break;
                        default:
                            break;
                    }
                    m = m.NextMatch();
                }
            }

            //==================================================================================================================
            //Get Screenshot Images
            fullHtmlContent = fullHtmlContent.Replace("[SCREENSHOTS]", imgDict[1]);

            //==================================================================================================================
            //Get downloadfile
            FilePost objFilePost = new FilePost();
            string downloadFiles = objFilePost.GetHtmlCode(Post.PostId, useHideTag, isHostContraint);
            if (fullHtmlContent.Contains("[DOWNLOADS]"))
                fullHtmlContent = fullHtmlContent.Replace("[DOWNLOADS]", downloadFiles);
            else
                fullHtmlContent += string.Format("\n[B][U]Download links:[/U][/B]\n{0}",downloadFiles);
            return fullHtmlContent;
            
        }

        /// <summary>
        /// //Check response url is a link of the post?
        /// </summary>
        /// <param name="postTitle"></param>
        /// <param name="responseUrl"></param>
        /// <returns></returns>
        public bool IsThreadUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                return false;

            bool result = false;
            //Check postUrl is a link of the post?
            string[] words = PostTitle.Split(new char[] { ' ' });
            
            string pattern = "(" + string.Join("|", words) + ")";
            Regex r = new Regex(pattern.ToLower().Trim());
            MatchCollection mc = r.Matches(url.ToLower().Trim());
            if (mc.Count > words.Count() - 2)
            {
                result = true;
            }
            else
            {
                pattern = @"showthread\.php\?p\=(?<threadId>[0-9]+)";
                r = new Regex(pattern);
                Match m1 = r.Match(url.ToLower().Trim());
                if (m1.Success)
                {
                    result = true;
                }
            }
            return result;
        }
    }

    partial class Post
    {
        LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        public Post GetPost(int postId)
        {
            Post obj = dc.Posts.Single(p => p.PostId == postId);
            return obj;
        }

        public IQueryable<Post> GetAll()
        {
            var query = from p in dc.Posts
                        select p;
            return query;
        }

        public int GetHostIconByPost(int postId)
        {
            int iconId = -1;
            var query = (from p in dc.FilePosts
                        where p.PostId == postId
                        select p.HostId).Distinct();
            //if file post count > 1 then select multi icon
            if (query.Count() > 1) 
            {
                var query1 = from q in dc.ForumHosts
                             where q.HostId == (int)enumIcon.Multi //multi host icon
                             select q.IconNumber;
                // Has value
                if (query1.Count() > 0)
                {
                    foreach (int id in query1)
                        iconId = id;
                }
            }
            else //select exactly host icon
            {
                int hostId = -1;
                foreach (int id in query)
                    hostId = id;

                var query1 = from q in dc.ForumHosts
                             where q.HostId == hostId //get exactly host icon
                             select q.IconNumber;
                // Has value
                if (query1.Count() > 0)
                {
                    foreach (int id in query1)
                        iconId = id;
                }
            }
            return iconId;

        }

        public IQueryable<Post> GetPostsByTopic(string topicIds)
        {
            List<string> topicIdList = topicIds.Split(new char[] { '|' }).ToList();
            IQueryable<Post> query = (from p in dc.Posts
                                      where topicIdList.Contains(p.TopicId.ToString())
                                      select p).OrderBy(t => t.PostId);//(t => t.Topic.TopicOrder);

            return query;
        }

        public void SetApproved(int postId, bool isApproved)
        {
            Post objPost = dc.Posts.Single(p => p.PostId == postId);
            objPost.IsApproved = isApproved;
            dc.SubmitChanges();
        }

        //public IQueryable<Post> GetPostByQuery(int postId)
        //{
        //    LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        //    IQueryable<Post> query = from p in dc.Posts
        //                             where p.PostId == postId
        //                             select p;
        //    return query;
        //}
    }

    partial class StatusCode
    {
        public int GetStatusCodeId(int code)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.StatusCodes
                        where p.Code == code
                        select p;
            int id = -1;
            if (query.Count() == 0) //Nếu không tìm  thấy thì insert Language
            {
                StatusCode sc = new StatusCode
                {
                    _Code = code
                };
                dc.StatusCodes.InsertOnSubmit(sc);
                dc.SubmitChanges();
                id = sc.StatusCodeId;
            }
            else
            {
                foreach (StatusCode sc in query)
                    id = sc.StatusCodeId;
            }

            return id;
        }
    }

    partial class Location
    {
        public Location GetLocation(int locationId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Location obj;
            try
            {
                obj = dc.Locations.Single(p => p.LocationId == locationId);
            }
            catch
            {
                obj = null;
            }
            return obj;
        }

        public int GetLocationId(string locationName)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.Locations
                        where p.LocationName == locationName.ToLower()
                        select p;
            int id = -1;
            if (query.Count() == 0) //Nếu không tìm  thấy thì insert Language
            {
                Location loc = new Location
                {
                    _LocationName = locationName
                };
                dc.Locations.InsertOnSubmit(loc);
                dc.SubmitChanges();
                id = loc.LocationId;
            }
            else
            {
                foreach (Location loc in query)
                    id = loc.LocationId;
            }

            return id;
        }
    }

    partial class Post
    {
        public Post LoadSamplePost()
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            return dc.Posts.Single(p => p.PostId == 2);
        }
        public void AddNewPost(string title, string content)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Post obj = new Post
            {
                PostTitle = title
            };

            dc.Posts.InsertOnSubmit(obj);

            // Submit the change to the database.
            try
            {
                dc.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }

        }
    }

    partial class ContentType
    {
        public ContentType GetContentType(int contentTypeId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ContentType obj;
            try
            {
                obj = dc.ContentTypes.Single(p => p.ContentTypeId == contentTypeId);
            }
            catch
            {
                obj = null;
            }
            return obj;
        }

        public string GetKeyWords(int contentTypeId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.ContentTypes
                        where p.ContentTypeId == contentTypeId
                        select new
                        {
                            Keywords = p.Keywords
                        };

            string result = "";
            foreach (var q in query)
                result = q.Keywords;
            return result;
        }

        /// <summary>
        /// Indentify content of a forum is App, App-Porn or Porn
        /// </summary>
        /// <param name="content"> </param>
        /// <returns></returns>
        public int IdentifyForumContent(string content)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            int result = (int)enumContentType.Unknown; //Unknown
            //App keywords
            string appKeywords = GetKeyWords(1);
            Regex appRegex = new Regex("(" + appKeywords + ")");
            MatchCollection appMatch = appRegex.Matches(content);

            //Porn keywords
            string pornKeywords = GetKeyWords(2);
            Regex pornRegex = new Regex("(" + pornKeywords + ")");
            MatchCollection pornMatch = pornRegex.Matches(content);
            //Check the forum is a application forum
            if (appMatch.Count >= 3)
            {
                result = (int)enumContentType.App; //App
                //Check the forum is also a porn forum
                if (pornMatch.Count >= 3)
                    result = (int)enumContentType.App_Porn; //App-Porn
            }
            else
            {
                //Check the forum is also a porn forum
                if (pornMatch.Count > 3)
                    result = (int)enumContentType.Porn; //Porn
            }
            return result;
        }
    }

    partial class Account
    {
        public Account GetAccount(int accountId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            Account acc = dc.Accounts.Single(p => p.AccountId == accountId);
            return acc;
        }
    }

    partial class ForumType
    {
        //public string GetLoginUrl(int forumTypeId)
        //{
        //    LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        //    var query = from p in dc.ForumTypes
        //                where p.ForumTypeId == forumTypeId
        //                select new
        //                {
        //                    LoginUrl = p.LoginUrl
        //                };
        //    string url = "";
        //    foreach (var q in query)
        //        url = q.LoginUrl;
        //    return url;
        //}

        //public string GetRegisterUrl(int forumTypeId)
        //{
        //    LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        //    var query = from p in dc.ForumTypes
        //                where p.ForumTypeId == forumTypeId
        //                select new
        //                {
        //                    RegisterUrl = p.RegisterUrl
        //                };
        //    string url = "";
        //    foreach (var q in query)
        //        url = q.RegisterUrl;
        //    return url;
        //}

        //public string GetBlackListUrl(int? forumTypeId)
        //{
        //    LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
        //    var query = from p in dc.ForumTypes
        //                where p.ForumTypeId == forumTypeId
        //                select new
        //                {
        //                    BacklistUrl = p.BacklistUrl
        //                };
        //    string url = "";
        //    foreach (var q in query)
        //        url = q.BacklistUrl;
        //    url = "(" + url.Replace(@".", @"\.") + ")";
        //    return url;
        //}

        public ForumType GetForumType(int forumTypeId)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumType obj;
            try
            {
                obj = dc.ForumTypes.Single(p => p.ForumTypeId == forumTypeId);
            }
            catch
            {
                obj = null;
            }
            return obj;
        }

        public ForumType GetForumTypeId(string typeName)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            ForumType objForumType = dc.ForumTypes.Single(p => p.TypeName == typeName);
            return objForumType;
        }

        public IQueryable<ForumType> GetRootForumType()
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            IQueryable<ForumType> query = from p in dc.ForumTypes
                                          where p.ParentForumTypeId == null
                                          select p;
            return query;
        }
    }

    partial class Language
    {
        public int GetLangId(string langName)
        {
            LinqDataClassesDataContext dc = new LinqDataClassesDataContext();
            var query = from p in dc.Languages
                        where p.LanguageName == langName.ToLower()
                        select new
                        {
                            LanguageId = p.LanguageId
                        };
            int id = -1;
            if (query.Count() == 0) //Nếu không tìm  thấy thì insert Language
            {
                Language lang = new Language
                {
                    _LanguageName = langName
                };
                dc.Languages.InsertOnSubmit(lang);
                dc.SubmitChanges();
                id = lang._LanguageId;
            }
            else
            {
                foreach (var q in query)
                    id = q.LanguageId;
            }

            return id;
        }

    }
}





